package com.hj.controller;

import cn.hutool.core.util.IdUtil;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.hj.tools.RedisUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author < a href="huajian2018@aliyun.com">hj</ a>
 * @Description 测试获取图形验证码
 */
@RequestMapping("/kaptcha")
@Controller
public class TestKaptchaController {

    private final DefaultKaptcha defaultKaptcha;
    private final RedisUtil redisUtils;

    public TestKaptchaController(DefaultKaptcha defaultKaptcha, RedisUtil redisUtils) {
        this.defaultKaptcha = defaultKaptcha;
        this.redisUtils = redisUtils;
    }

    @GetMapping(value = "/kaptchaImage")
    public void getCaptchaImage(HttpServletRequest request, HttpServletResponse response) throws IOException {

        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");

        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        String capText = defaultKaptcha.createText();
        System.out.println("capText: " + capText);
        try {
            String uuid = IdUtil.simpleUUID();
            redisUtils.set(uuid, capText, 3 * 60L);
            Cookie cookie = new Cookie("kaptchaCode", uuid);
            cookie.setPath("/");
            response.addCookie(cookie);
        } catch (Exception e) {
            e.printStackTrace();
        }
        BufferedImage bi = defaultKaptcha.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }


}
